#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <windows.h>

int main() {
    const std::string baseFileName = "testfile_";
    std::vector<std::ofstream*> filePointers;
    int fileIndex = 0;

    try {
        while (true) {
            std::string fileName = baseFileName + std::to_string(fileIndex++);
            std::ofstream* file = new std::ofstream(fileName, std::ios::out | std::ios::binary);

            // Check if the file was successfully opened
            if (!file->is_open()) {
                throw std::runtime_error("Failed to open file: " + fileName);
            }

            // Store the file pointer for later closing
            filePointers.push_back(file);

            // Optionally, print out the number of files opened so far
            std::cout << "Opened file: " << fileName << ", Total opened: " << filePointers.size() << std::endl;

            // Sleep for a short duration to avoid overwhelming the system (optional)
            Sleep(1); // Sleep for 2 millisecond
        }
    }
    catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << ", Total opened: " << filePointers.size() << std::endl;
        system("pause");
    }

    // Close all opened files
    for (std::ofstream* file : filePointers) {
        file->close();
        delete file;
    }

    // Optionally, delete the created files
    for (unsigned int i = 0; i < filePointers.size(); ++i) {
        std::string fileName = baseFileName + std::to_string(i);
        if (DeleteFileA(fileName.c_str()) == 0) {
            std::cerr << "Failed to delete file: " << fileName << ", Error: " << GetLastError() << std::endl;
        }
    }

    return 0;
}